//
//  DetailViewController.swift
//  XiaoXiangMu1604
//
//  Created by qianfeng on 16/9/27.
//  Copyright © 2016年 SunPiaoLiang. All rights reserved.
//

import UIKit

//系统库  定位用
import CoreLocation

class DetailViewController: LFNavigationViewController {

    //应用的ID值
    var appId : String?
    
    //详情的数据
    private var detailModel: DetailModel?
    //定位对象
    private var manager: CLLocationManager?
    
    //下载详情是否成功
    private var detailSuccess: Bool?
    
    //下载附近是否成功
    private var nearBysuccess: Bool?
    
    //是否已经下载附近数据
    private var isNearByDownload: Bool?
    
    @IBOutlet weak var appImageView: UIImageView!
    
    @IBOutlet weak var nameLabel: UILabel!
    
    @IBOutlet weak var lastPriceLabel: UILabel!
    
    @IBOutlet weak var statusLabel: UILabel!
    
    @IBOutlet weak var sizeLabel: UILabel!
    
    @IBOutlet weak var categoryLabel: UILabel!
    
    @IBOutlet weak var rateLabel: UILabel!
   
    @IBOutlet weak var shareButton: UIButton!
    
    @IBOutlet weak var favoriteButton: UIButton!
    
    @IBOutlet weak var downloadButton: UIButton!
    
    @IBOutlet weak var imageScrollView: UIScrollView!
    
    @IBOutlet weak var descLabel: UILabel!
    
    @IBOutlet weak var nearByScrollView: UIScrollView!
    
    @IBAction func shareButtonAction() {
        
        
        
    }
    
    
    @IBAction func favoriteButtonAction() {
        
        //创建收藏的数据对象
        if appImageView.image != nil {
            
            //图片数据下载完成后才能收藏
            let model = CollectModel()
            model.applicationId = detailModel?.applicationId
            model.name = detailModel?.name
            model.headImage = appImageView.image
            
            let dbManager = LFDBManager()
            dbManager.addCollect(model,finishClosure: {
                flag in
                if flag == true {
                    MyUtil.showAlertMsg("收藏成功", onViewController: self)
                    
                    self.refreshAppState()
                    
                    
                }else{
                    MyUtil.showAlertMsg("收藏失败", onViewController: self)
                }
            })
            
        }else {
            
            MyUtil.showAlertMsg("数据正在下载，稍后再收藏", onViewController: self)
        }

        
    }
    
    @IBAction func downloadButtonAction() {
        
         //打开AppStore
        if detailModel?.itunesUrl != nil{
            
            let url = NSURL(string:(detailModel?.itunesUrl)!)
            
            if UIApplication.sharedApplication().canOpenURL(url!){
                
                UIApplication.sharedApplication().openURL(url!)
                
                
            }
            
            
        }
        
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        ProgressHUD.showOnView(view)
        
        downloadDetailData()
        
        createMyNav()
        
        locate()
        
        //判断是否已经收藏
        verifyAppState()
    
    }
    //判断是否已经收藏
    func verifyAppState(){
        
        let dbManager = LFDBManager()
        
        dbManager.isAppFavorite(appId!)
            {
                (flag) in
                
                //如果已收藏，不让用户在收藏
                if flag == true{
                    
                   self.refreshAppState()
                    
                }
                
        }
        
    
    }
    
    //监测收藏的状态
    func refreshAppState(){
        
        dispatch_async(dispatch_get_main_queue()) {
            
            
            self.favoriteButton.setTitle("已收藏" ,forState: .Normal)
            
            self.favoriteButton.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
            
            self.favoriteButton.enabled = false
            
            
        }
        
        
    }
    //定位
    func locate(){
        
        manager = CLLocationManager()
        
        manager?.distanceFilter = 10
        
        manager?.desiredAccuracy = kCLLocationAccuracyBest
        
        //定位请求
        if manager?.respondsToSelector("requestWhenInUseAuthorization") == true{
            
            manager?.requestWhenInUseAuthorization()
            
        }
        manager?.delegate = self
        
        manager?.startUpdatingLocation()
        
        
    }
    
    //导航
    func createMyNav(){
       
        addNavTitle("应用详情")
        
        //返回按钮
        addBackButton()
    }
    //下载详情数据
    func downloadDetailData(){
        
        let urlString = String(format: kDetailUrl , appId! )
        
        let d = LFDownloader()
        
        d.delegate = self
        
        d.type = .Detail
        
        d.downloadWithURLString(urlString)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    func showDetail(){
        
        let url = NSURL(string:(detailModel?.iconUrl)!)
        
        appImageView.kf_setImageWithURL(url!)
        
        nameLabel.text = detailModel?.name
        
        lastPriceLabel.text = "原价" + (detailModel?.lastPrice)!
        
        if detailModel?.priceTrend == "limited"{
            
            statusLabel.text = "限免中"
            
        }else if detailModel?.priceTrend == "sales"{
            
            statusLabel.text = "降价中"
            
        }else if detailModel?.priceTrend == "free"{
            
            statusLabel.text = "免费中"
            
        }
        
        sizeLabel.text = (detailModel?.fileSize)! + "MB"
        
        categoryLabel.text = MyUtil.transferCateName((detailModel?.categoryName)!)
        
        rateLabel.text = "评分" + (detailModel?.starCurrent)!
        
        let cnt = detailModel?.photos?.count
        
        let imageH = CGFloat(80)
        
        let imageW = CGFloat(80)
        
        let marginX = CGFloat(10) //图片的横向间距
        
       
        for i in 0..<cnt!{
            
            let frame = CGRectMake((marginX + imageW)*CGFloat(i), 0, imageW, imageH)
                        
            let pModel = detailModel?.photos![i]
            
            let url = NSURL(string: (pModel?.smallUrl)!)
            
            let tmpImageView = UIImageView(frame: frame)

            tmpImageView.kf_setImageWithURL(url!)
            
            
            //添加手势
            let g = UITapGestureRecognizer(target: self, action: "tapImage:")
            
            tmpImageView.addGestureRecognizer(g)
            
            tmpImageView.userInteractionEnabled = true
            
            tmpImageView.tag = 100 + i
            
            imageScrollView.addSubview(tmpImageView)
            
        }
        
        imageScrollView.contentSize = CGSizeMake((imageW + marginX)*CGFloat(cnt!), 0)
        
        descLabel.text = detailModel?.desc
        
    }
    func tapImage(g:UIGestureRecognizer){
        
        let index = (g.view?.tag)! - 100
        
        let photoCtl = PhotoViewController()
        
        photoCtl.modalTransitionStyle = .FlipHorizontal
        
        //点击图片的序列
        photoCtl.photoIndex = index
        
        //所有图片的数据
        photoCtl.photoArray = detailModel?.photos
        
        presentViewController(photoCtl, animated: true, completion: nil)
        
        
    }

    //详情的解析
    func parseDetailData(data:NSData){
        
        let resule = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
        
        if resule.isKindOfClass(NSDictionary){
            
            let dict = resule as! Dictionary<String,AnyObject>
            
            detailModel = DetailModel()
            
            detailModel?.setValuesForKeysWithDictionary(dict)
            
            var pArray = Array<PhotoModel>()
            
            for pDict in (dict["photos"] as! NSArray){
                
                let model = PhotoModel()
                
                model.setValuesForKeysWithDictionary(pDict as! [String:AnyObject])
                
                pArray.append(model)
                
                
            }
            detailModel?.photos = pArray
            
            //回到主线程修改UI
            dispatch_async(dispatch_get_main_queue(), {
                
                //将其封装成一个方法，调用该方法即可
                self.showDetail()
                
                
            })
            
            
        }
        
        
    }
    //显示附近的数据
    func showNearData(array:Array<LimitModel>){
        
        let btnW:CGFloat = 80
        
        let btnH:CGFloat = 80
        
        let marginX:CGFloat = 10 //按钮横向的间距
        
        for i in 0..<array.count{
            
            let model = array[i]
            
            let btn = NearbyButton(frame:CGRectMake((10+btnW + marginX)*CGFloat(i),0,btnW,btnH))
            
            //添加点击事件
            btn.addTarget(self, action: "clickBtn:", forControlEvents: .TouchUpInside)
            
            btn.model = model
            
            nearByScrollView.addSubview(btn)
            
        }
        
        let a = ( btnW + marginX)*CGFloat(array.count)
        //print(a)
        nearByScrollView.contentSize = CGSizeMake(( btnW + marginX)*CGFloat(array.count), 0)
        
        
    }
    //按钮的响应事件
    func clickBtn(btn:NearbyButton){
        
        let model = btn.model
        
        //跳转详情
        let detailCtl = DetailViewController()
        
        detailCtl.appId = btn.model?.applicationId
        
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(detailCtl, animated: true)
        
    }
    //附近数据的解析
    func parseNearByData(data:NSData){
    
        let result = try!NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
        
        if result.isKindOfClass(NSDictionary){
            
            let dict = result as! Dictionary<String,AnyObject>
            
            let array = dict["applications"] as! Array<Dictionary<String,AnyObject>>
        
            
            //数据数组
            var modelArray = Array<LimitModel>()
            
            for appDict in array{
                
                let model = LimitModel()
                
                model.setValuesForKeysWithDictionary(appDict)
                
                modelArray.append(model)
                
            }
            
            //显示数据
            dispatch_async(dispatch_get_main_queue(), {
                
                self.showNearData(modelArray)
                
            })
            
        }
        
    }


}
extension DetailViewController:LFDownloaderDelegate{
    
    func downloader(downloader: LFDownloader, didFailWithError error: NSError) {
        
        if downloader.type == .Detail{
            
            detailSuccess = false
            
        }else if downloader.type == .NearBy{
            
            nearBysuccess = false
            
        }
    
        //两个都失败才算失败
        if detailSuccess == false && nearBysuccess == false{
            
            dispatch_async(dispatch_get_main_queue(), {
                
                ProgressHUD.hideAfterFailOnView(self.view)
                

            })
            
        }
    }
    
        func downloader(downloader: LFDownloader, didFinishWithData data: NSData) {
        
        if downloader.type == .Detail{
            
            self.parseDetailData(data)
            
            detailSuccess = true
            
        }else if downloader.type == .NearBy{
            
           self.parseNearByData(data)
            
            nearBysuccess = true
            
        }
        
        if detailSuccess == false && nearBysuccess == false{
            
            
        }else{
            
            dispatch_async(dispatch_get_main_queue(), {
            
                ProgressHUD.hideAfterSuccessOnView(self.view)
            
            })
            
            
        }
        
    }
    
}
//MARK:CllocationManager的代理
extension DetailViewController:CLLocationManagerDelegate{
    
    
    //判断是不是模拟器的问题
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        
        print(error)
        
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        let loc = locations.last
        
        if loc?.coordinate.latitude != nil && loc?.coordinate.longitude != nil && (isNearByDownload != true){
            
            //请求附近的数据
            let urlString = String(format: kNearByUrl, (loc?.coordinate.longitude)!,(loc?.coordinate.latitude)!)
            
            let d = LFDownloader()
            
            d.delegate = self
            
            d.type = .NearBy
            
            d.downloadWithURLString(urlString)
            
            //结束定位
            manager.stopUpdatingLocation()
            
            isNearByDownload = true

            
        }
        
    }
    
  }
